﻿#define  _CRT_SECURE_NO_WARNINGS 1
#include"SeqList.h"

void SLInit(SL* ps)
{
    ps->arr = NULL;
    ps->size = 0;
    ps->capacity = 0;
}

void SLPrint(SL* ps)
{
    for (int i = 0; i < ps->size; i++)
    {
        printf("%d ", ps->arr[i]);
    }
    printf("\n");
}

void CheckCapacity(SL* ps)
{
    assert(ps);
    if (ps->size == ps->capacity)
    {
        int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
        SLDataType* tmp = (SLDataType*)realloc(ps->arr, newCapacity * sizeof(SLDataType));
        if (!tmp)
        {
            perror("Realloc Failed!\n");
            exit(1);
        }
        ps->arr = tmp;
        ps->capacity = newCapacity;
    }
}

void SLPushBack(SL* ps, SLDataType x)
{
    assert(ps);
    CheckCapacity(ps);
    ps->arr[ps->size++] = x;
}
void SLPushFront(SL* ps, SLDataType x)
{
    assert(ps);
    CheckCapacity(ps);
    for (int i = ps->size; i > 0; i--)
    {
        ps->arr[i] = ps->arr[i - 1];
    }
    ps->arr[0] = x;
    ps->size++;
}
void SLInsertBefore(SL* ps, int pos, SLDataType x)
{
    assert(ps && pos >= 0 && pos < ps->size);
    CheckCapacity(ps);
    for (int i = ps->size; i > pos; i--)
    {
        ps->arr[i] = ps->arr[i - 1];
    }
    ps->arr[pos] = x;
    ps->size++;
}
void SLInsertAfter(SL* ps, int pos, SLDataType x)
{
    assert(ps && pos >= 0 && pos < ps->size);
    //等价于在pos+1位置前添加元素
    SLInsertBefore(ps, pos + 1, x);
}

void SLPopBack(SL* ps)
{
    assert(ps);
    --ps->size;
}
void SLPopFront(SL* ps)
{
    assert(ps);
    for (int i = 1; i < ps->size; i++)
    {
        ps->arr[i - 1] = ps->arr[i];
    }
   ps->size--;
}
void SLErase(SL* ps, int pos)
{
    assert(ps && pos >= 0 && pos < ps->size);
    for (int i = pos + 1; i < ps->size; i++)
    {
        ps->arr[i - 1] = ps->arr[i];
    }
    ps->size--;
}

int SLFind(SL* ps, SLDataType x)
{
    assert(ps);
    for (int i = 0; i < ps->size; i++)
    {
        if (ps->arr[i] == x) return i;
    }
    return -1;
}

void SLChange(SL* ps, int pos, SLDataType x)
{
    assert(ps && pos >= 0 && pos < ps->size);
    ps->arr[pos] = x;
}

void SLDestroy(SL* ps)
{
    if (ps->arr)
    {
        free(ps->arr);
    }
    ps->arr = NULL;
    ps->size = ps->capacity = 0;
}
​

; ;